package com.wenguo.common.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.util.UrlPathHelper;

import com.wenguo.Constants;


public final class URLHelper {
	
	private URLHelper() {
		
	}
	
	/**
	 * 获得翻页信息
	 * 
	 * @param request
	 * @return
	 */
	public static PageInfo getPageInfo(HttpServletRequest request) {
		String uri = getURI(request);
		String queryString = getQueryString(request);
		return getPageInfo(uri, queryString);
	}
	
	/**
	 * 获得URL信息
	 * 
	 * @param uri
	 *            URI {@link HttpServletRequest#getRequestURI()}
	 * @param queryString
	 *            查询字符串 {@link HttpServletRequest#getQueryString()}
	 * @return
	 */
	public static PageInfo getPageInfo(String uri, String queryString) {
		if (uri == null) {
			return null;
		}
		if (!uri.startsWith("/")) {
			throw new IllegalArgumentException("URI must start width '/'");
		}
		int flag = uri.indexOf(Constants.system.URL_PAGE_SYMBOL);
		int bi;
		int mi;
		int pi;
		if (flag > -1) {
			bi = uri.lastIndexOf("/") + 1;
			mi = uri.length();
			pi = flag + Constants.system.URL_PAGE_SYMBOL.length();
		} else {
			bi = uri.length();
			mi = -2;
			pi = -2;
		}
		
		Integer pageNo = 1;
		if (mi > -1 && flag > -1) {
			pageNo = Integer.parseInt(uri.substring(pi, mi));
		} 

		// 翻页后半部
		String urlLater = "";
		Map<String, String> params = null;
		
		if (!StringUtils.isBlank(queryString)) {
			params = getParams(queryString);
			if (!params.isEmpty()) { 
				urlLater = "?";
				for (Map.Entry<String, String> p : params.entrySet()) {
					urlLater += p.getKey() + "=" + p.getValue();
				}
			}
		} 
		String href = uri.substring(0, bi);
		if (!href.endsWith("/")) {
			href += "/";
		}
		return new PageInfo(href, Constants.system.URL_PAGE_SYMBOL, urlLater, pageNo, 0, params);
	}
	
	/**
	 * get query params
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> getParamsMap(HttpServletRequest request) {
		return getParamsMap(getQueryString(request));
	}
	
	/**
	 * get query params
	 * 
	 * @param queryString
	 * @return
	 */
	public static Map<String, String> getParams(String queryString) {
		return getParamsMap(queryString);
	}
	
	
	
//	public static Log getLogInfo(User user, HttpServletRequest request) {
//		Log log = new Log();
//		String[] s = RequestUtil.getLogRequest(request);
//		log.setIp(s[0]);
//		log.setDate(s[1]);
//		log.setUid(user.getId());
//		return log;
//	}
	
	//-----------------------------------------------
	
	public static String getContextPath(HttpServletRequest request) {
		UrlPathHelper helper = new UrlPathHelper();
		return helper.getOriginatingContextPath(request);
	}
	
	public static String getURI(HttpServletRequest request) {
		UrlPathHelper helper = new UrlPathHelper();
		String uri = helper.getRequestUri(request);
		String ctx = helper.getContextPath(request);
		if (!StringUtils.isBlank(ctx)) {
			return uri.substring(ctx.length());
		} else {
			return uri;
		}
	}
	
	private static String getQueryString(HttpServletRequest request) {
		UrlPathHelper helper = new UrlPathHelper();
		String queryString = helper.getOriginatingQueryString(request);
		return queryString;
	}
	
	/**
	 * 获得路径参数
	 * 
	 * @param uri
	 * @return
	 */
	public static Map<String, String> getParamsMap(String uri) {
		if (uri == null) {
			return null;
		}
		Map<String, String> params = new HashMap<String, String>();
		String[] qstring = uri.split("&");
		for (String s : qstring) {
			String[] q = s.split("=");
			if (!Constants.system.TOKEN.equals(q[0])) {
				params.put(q[0], q[1]);
			}
		}
		return params;
	}
	
	//----------------------------------------------
	
	public static class PageInfo {
		/**
		 * 页面地址
		 */
		private String href;
		/**
		 * href前半部（相对于分页）
		 */
		private String hrefFormer = "";
		/**
		 * href后半部（相对于分页）
		 */
		private String hrefLatter = "";
		/**
		 * page size
		 */
		private Integer pageSize = Constants.system.PAGE_SIZE2;
		/**
		 * page number
		 */
		private Integer pageNo = 1;
		/**
		 * total page
		 */
		private Integer totalPage = 1;
		/**
		 * total number
		 */
		private Long totalCount = 1L;
		/**
		 * query params Map
		 */
		private Map<String, String> queryMap = null;
		
		public PageInfo() {
			
		}

		public PageInfo(String href, String hrefFormer, String hrefLatter,
				Integer pageNo, Integer totalPage, Map<String, String> queryMap) {
			this.href = href;
			this.hrefFormer = hrefFormer;
			this.hrefLatter = hrefLatter;
			this.pageNo = pageNo;
			this.totalPage = totalPage;
			this.queryMap = queryMap;
		}

		public String getHref() {
			return href;
		}
		public void setHref(String href) {
			this.href = href;
		}
		public Integer getPageNo() {
			return pageNo;
		}
		public void setPageNo(Integer pageNo) {
			this.pageNo = pageNo;
		}
		public Integer getTotalPage() {
			return totalPage;
		}
		public void setTotalPage(Integer totalPage) {
			this.totalPage = totalPage;
		}
		public String getHrefFormer() {
			return hrefFormer;
		}
		public void setHrefFormer(String hrefFormer) {
			this.hrefFormer = hrefFormer;
		}
		public String getHrefLatter() {
			return hrefLatter;
		}
		public void setHrefLatter(String hrefLatter) {
			this.hrefLatter = hrefLatter;
		}
		public Map<String, String> getQueryMap() {
			return queryMap;
		}
		public void setQueryMap(Map<String, String> queryMap) {
			this.queryMap = queryMap;
		}
		public Integer getPageSize() {
			return pageSize;
		}
		public void setPageSize(Integer pageSize) {
			this.pageSize = pageSize;
		}
		public Long getTotalCount() {
			return totalCount;
		}
		public void setTotalCount(Long totalCount) {
			this.totalCount = totalCount;
			Long ps = new Long(pageSize);
			Long pz = totalCount / ps;
			pz = totalCount % ps == 0 ? pz : pz + 1;
			this.setTotalPage(Integer.parseInt(pz.toString()));
		}

		@Override
		public String toString() {
			StringBuilder sb = new StringBuilder();
	        sb.append("href: ").append(href).append(",");
	        sb.append("hrefFormer: ").append(hrefFormer).append(",");
	        sb.append("hrefLatter: ").append(hrefLatter).append(",");
	        sb.append("totalCount: ").append(totalCount).append(",");
	        sb.append("pageSize: ").append(pageSize).append(",");
	        sb.append("pageNo: ").append(pageNo).append(",");
	        sb.append("totalPage: ").append(totalPage).append(",");
	        sb.append("queryMap: ").append(queryMap);
	        return sb.toString();
		}
		
	}

}
